<template>
  <div class="list" style="overflow:auto">
    <BannerInList :count="count" :queryData="queryData" />
    <Categorys />
    <List :gallery="gallery" ref="grid" :gridcount="gridcount" />
    <div style="width:100%;height:100%;" v-if="showLoading">
      <el-button
        v-if="showLoading"
        v-loading="showLoading"
        element-loading-text="拼命加载中"
        element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(255, 255, 255, 0.8)"
        style="width: 100%;height:600px;border:none"
      ></el-button>
    </div>
    <div v-if="isAllLoad" style="width:100%;margin:0 auto;text-align:center;margin-bottom:50px;">没有更多了...</div>
    <div class="footer">
      <div class="gotop el-icon-top" v-show="gotop" @click="toTop">返回顶部</div>
    </div>
  </div>
</template>


<script>
import BannerInList from "@/components/BannerInList.vue";
import Categorys from "@/components/Categorys.vue";
import List from "@/components/List.vue";
export default {
  name: "list",
  layout: "image_list",
  components: {
    Categorys,
    BannerInList,
    List
  },
  data() {
    return {
      gotop: false,
      gallery: [],
      keyWords: "",
      page: 1,
      pagesize: 15,
      showLoading: false,
      count: 0,
      flexinit:false,
      gridcount:0,
      islayout:false,
      lazyloadThrottle:-1,      
      imgList:[],
      queryData: {} //请求的类型及参数
    };
  },
  computed: {
    isAllLoad() {
      if (this.gallery.length >= this.count) {
        return true;
      } else {
        return false;
      }
    }
  },
  watch: {
    $route: {
      handler: function() {
        this.gallery = [];
        this.queryData = this.$route.query;
        this.load(this.queryData);
      },
      // 深度观察监听
      deep: true
    }
  },

  created() {
    this.queryData = this.$route.query;
    this.load(this.queryData);
  },
  mounted() {
    window.addEventListener("scroll", this.onScroll, true);
    window.addEventListener("scroll", this.handleScroll, true);
    let swidth = this.$el.offsetWidth
    this.gridcount = parseInt(swidth/460)

    window.onresize = (e)=>{
      if( this.flexinit ) return;
      let w = parseInt(this.$el.offsetWidth / 460 )
      if( w > this.gridcount || this.gridcount > w){
        this.flexinit = true
        this.gridcount = w
        setTimeout(()=>{
          this.$refs.grid.load(this.imgList)
        })
      }
    }
  },
  methods: {
    handleScroll() {
      let scrolltop =
        document.documentElement.scrollTop || document.body.scrollTop;
      scrolltop > 30 ? (this.gotop = true) : (this.gotop = false);
    },
    toTop() {
      window.scrollTo(0, 0);
      // let top = document.documentElement.scrollTop || document.body.scrollTop;
      // // 实现滚动效果
      // const timeTop = setInterval(() => {
      //   document.body.scrollTop = document.documentElement.scrollTop = top -= 50;
      //   if (top <= 0) {
      //     clearInterval(timeTop);
      //   }
      // }, 10);
    },
    onScroll() {
      // // 可滚动容器的高度
      // // let innerHeight = document.querySelector("#__nuxt").clientHeight;
      // let innerHeight = document.querySelector(".list").clientHeight;
      // // 屏幕尺寸高度
      // let outerHeight = document.documentElement.clientHeight;
      // // 可滚动容器超出当前窗口显示范围的高度
      // let scrollTop =
      //   document.documentElement.scrollTop ||
      //   window.pageYOffset ||
      //   document.body.scrollTop;
      // // scrollTop在页面为滚动时为0，开始滚动后，慢慢增加，滚动到页面底部时，出现innerHeight <= (outerHeight + scrollTop)的情况，严格来讲，是接近底部。
      // // console.log('可滚动容器的高度:' + innerHeight, '屏幕尺寸高度:' + outerHeight, '可滚动容器超出当前窗口显示范围的高度:' + scrollTop)
      // if (outerHeight + scrollTop >= innerHeight - 1) {
      //   if (this.count > this.gallery.length) {
      //     // 加载更多操作
      //     this.showLoading = true;
      //     this.page += 1;
      //     this.load(this.queryData);
      //   }
      // }
      if( this.flexinit ) return;
      let y = document.documentElement.scrollHeight - document.documentElement.scrollTop -1
      let ry = Math.round((document.documentElement.scrollHeight-document.documentElement.scrollTop)/document.documentElement.clientHeight)
      if (this.lazyloadThrottle) {
        clearTimeout(this.lazyloadThrottle);
      }

      this.lazyloadThrottle = setTimeout(() => {
        let fristlazy = document.querySelector("img.lazy")
        if( fristlazy !== null ){
          let p = fristlazy.parentElement.parentElement; 
          if( y - p.offsetTop < 600 ){
            //console.log(fristlazy.offsetTop, y )
            let lazyloadImages = document.querySelectorAll("img.lazy")
            lazyloadImages.forEach(function (img) {
              img.src = img.dataset.src
              img.classList.remove('lazy')
            })
          }
        }
      }, 20)

      if( !this.islayout && ry == 3 ){
        this.islayout = true
        this.$refs.grid.layout()
      }
      if (  y < document.documentElement.clientHeight) {
        this.flexinit = true
        this.page++
        this.load(this.queryData);
      }
    },

    load(params) {
      this.showLoading = true;
      let {
        keyWords = null,
        tag_id = null,
        category_id = null,
        topic_id = null,
        getNew = null
      } = params;
      let page = this.page;
      let pagesize = this.pagesize;
      var url = "";
      if (keyWords !== null) {
        url = "/api/web/getImgList";
      } else if (tag_id !== null && category_id != null) {
        tag_id = this.queryData.tag_id.split("|");
        url = "/api/web/getImageLikely";
      } else if (tag_id != null) {
        url = "/api/web/getImageByTag";
      } else if (category_id !== null) {
        url = "/api/web/getImageByCategory";
      } else if (topic_id !== null) {
        url = "/api/web/getImgListByTopic";
      } else if (getNew !== null) {
        url = "/api/web/getNewImg";
      }
      this.$axios
        .post(url, {
          queryData: { keyWords, tag_id, category_id, topic_id, getNew },
          page,
          pagesize
        })
        .then(res => {
          this.showLoading = false;
          this.count = res.data.count;
          //this.gallery.push(...res.data.rows);
          this.imgList.push(...res.data.rows);
          this.$refs.grid.load(this.imgList)
          this.islayout = false
          // console.log(this.gallery)
        })
        .catch(err => {
          console.log(err);
        });
    }
  },
  // 离开该页面需要移除这个监听的事件
  destroyed() {
    window.removeEventListener("scroll", this.onScroll, true);
    window.removeEventListener("scroll", this.handleScroll, true);
  }
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="less">
.list {
  min-height: 800px;
  .banner {
    margin-bottom: 48px;
  }
}
.footer .gotop {
  text-align: center;
  position: fixed;
  right: 50px;
  bottom: 30px;
  cursor: pointer;
  padding: 10px;
  border-radius: 5px;
  background: white;
  color: #000000;
  z-index: 2000;
}
</style>
